/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.ems.web.front;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.constant.Constant;
import com.thinkgem.jeesite.common.mapper.JsonMapper;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.cms.entity.Site;
import com.thinkgem.jeesite.modules.cms.utils.CmsUtils;
import com.thinkgem.jeesite.modules.ems.entity.EmsCart;
import com.thinkgem.jeesite.modules.ems.service.EmsCartService;
import com.thinkgem.jeesite.modules.sys.entity.Dict;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;

/**
 * 购物车Controller
 * @author zad
 * @version 2018-03-01
 */
@Controller
@RequestMapping(value = "${frontPath}/emsCart")
public class FrontCartController extends BaseController {

	@Autowired
	private EmsCartService emsCartService;
	
	@ModelAttribute
	public EmsCart get(@RequestParam(required=false) String id) {
		EmsCart entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = emsCartService.get(id);
		}
		if (entity == null){
			entity = new EmsCart();
		}
		return entity;
	}
	
	// add by zad 2018-02-03 查询自己的购物车
	@RequestMapping(value = {"myCartList"})
	public String myCartList(String discountType, EmsCart emsCart,String siteId, HttpServletRequest request, HttpServletResponse response, Model model) {
		
		Site site = CmsUtils.getSite(siteId);
		// 默认为微信站点
		if(!"weixin".equals(site.getTheme()))
		{
			site = CmsUtils.getSite(Site.weixinSiteId());
		}
		
		model.addAttribute("site", site);
		
		if(null != emsCart)
		{
			User user = UserUtils.getUser();
			emsCart.setCreateBy(user);
		}
		
		// 查询支付方式
		List<Dict> payTypes = DictUtils.getDictList("ems_pay_type");
		model.addAttribute("payTypes", payTypes);
		// 查询优惠方式
		List<Dict> discountTypes = DictUtils.getDictList("ems_discount_type");
		model.addAttribute("discountTypes", discountTypes);
		
		request.setAttribute("orderBy", "b.name");
		Page<EmsCart> pageParam = new Page<EmsCart>(request, response);
		pageParam.setOrderBy("b.name,b.mobile,a.create_date desc");
		Page<EmsCart> page = emsCartService.findPage(pageParam, emsCart); 
		
		/*Page<EmsCart> page = emsCartService.findPage(new Page<EmsCart>(request, response), emsCart); */
		model.addAttribute("page", page);
		
		// 循环购物车，做相关统计处理
		List<EmsCart> carts = null != page ? page.getList():null;
		// 当购物车内课程超过分页页面条数时，统计需要统计所有数据，此时需要重新查询所有数据
		if(null != page && null != page.getList() && page.getList().size() > page.getPageSize())
		{
			User loginUser = UserUtils.getUser();
			emsCart.setCreateBy(loginUser);
			carts = this.emsCartService.findList(emsCart);
		}
		if(StringUtils.isBlank(discountType))
		{
			discountType = discountTypes.get(0).getValue();
		}
		Map<String,String> map = this.emsCartService.analysisCartInfo(carts, discountType);
		model.addAttribute("map", map);
		model.addAttribute("discountType", discountType);
		
		return "modules/cms/front/themes/" + site.getTheme() + "/frontMyCartList";
	}

	// @RequiresPermissions("ems:emsCourse:view")
	@RequestMapping(value = "form")
	public String form(EmsCart emsCart, Model model) {
		model.addAttribute("emsCart", emsCart);
		return "modules/ems/emsCartForm";
	}

	// @RequiresPermissions("ems:emsCourse:view")
	@RequestMapping(value = "save")
	public String save(EmsCart emsCart, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, emsCart)){
			return form(emsCart, model);
		}
		if(null != emsCart)
		{
			emsCart.setStatus(Constant.CartHis.EMS_CARTHIS_STATUS_TOTRAIN);
		}
		emsCartService.save(emsCart);
		addMessage(redirectAttributes, "保存购物车成功");
		return "redirect:"+Global.getAdminPath()+"/ems/emsCart/?repage";
	}
	
	// @RequiresPermissions("ems:emsCourse:view")
	@RequestMapping(value = "delete")
	public String delete(EmsCart emsCart, RedirectAttributes redirectAttributes) {
		emsCartService.delete(emsCart);
		addMessage(redirectAttributes, "删除购物车成功");
		// return "redirect:"+Global.getAdminPath()+"/ems/emsCart/?repage";
		return "redirect:"+Global.getAdminPath()+"/ems/emsCart/myCartList?repage";
	}
	
	// add by zad 2018-01-26 查询购物车中当前用户商品数
	@RequestMapping("countCart")
	public String countCart(HttpServletRequest req,HttpServletResponse rsp)
	{
		Integer count = 0;
		User user = UserUtils.getUser();
		if(null != user)
		{
			count = emsCartService.countCart(user.getId());
			if(null == count)
			{
				count = new Integer(0);
			}
		}
		//List<EmsMajor> majors = this.emsMajorService.findList(major);
		//String jsonStr = JsonMapper.toJsonString(majors);
		try {
			rsp.getWriter().print(count);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	// 校验购物车是否重复
	// @RequiresPermissions("ems:emsCourse:view")
	@RequestMapping(value = {"checkExists"})
	public String checkExists(EmsCart emsCart, HttpServletRequest request, HttpServletResponse response, Model model) {
		
		Map<String,String> rs = new HashMap<String,String>();
		List<EmsCart> carts = this.emsCartService.checkExists(emsCart);
		if(null != carts && carts.size() > 0)
		{
			rs.put("rs", "yes");
		}
		else
		{
			rs.put("rs", "no");
		}
		
		String jsonStr = JsonMapper.toJsonString(rs);
		try {
			response.getWriter().print(jsonStr);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}